<script setup lang="tsx">
import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { reactive, ref } from 'vue'
import useSchema from './hooks/useSchema'
import { useCrudSchemas, AllSchemas } from '@/hooks/web/useCrudSchemas'
// @ts-ignore
import { FormRules } from 'element-plus'
import { UploadItem, SchemaConfig } from '@/api/attachment/types'
import { Dialog, TableDialog } from '@/components/Dialog'
import { preViewDialogStore } from '@/store/modules/preViewDialog'
import { useI18n } from '@/hooks/web/useI18n'
import { useTableDialogStore } from '@/store/modules/tableDialog'
import { getFieldEnumApi, getListApi } from '@/api/product'
import { getInfoApi } from '@/api/attachment'
import { CrudSchema } from '@/hooks/web/useCrudSchemas'
import { getBrandListApi } from '@/api/brand'
import { getCategorySelectTree } from '@/api/category'

const tableDialogStoreID = 'attachmentWrite'
const itemTitleName = 'cname'
const tableDialogStore = useTableDialogStore(tableDialogStoreID)

const tableDialogSelectedLimit = 1
defineOptions({
  name: 'AttachmentSave'
})

const { t } = useI18n()
const { query, ...route } = useRoute()
const props = withDefaults(
  defineProps<{
    index: number
    currentRow?: any
  }>(),
  {
    index: 0,
    currentRow: null
  }
)

const categoryList = ref([])
const brandList = ref([])
const fieldEnum = ref([])

const attachmentPreViewId = 'attachmentPreView'
const attachmentPreViewIdStore = preViewDialogStore(attachmentPreViewId)

const UploadArr = reactive<UploadItem[]>([])
const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods

// 定义表格对话框的 CRUD 模式
const tableDialogCurdSchema = reactive<CrudSchema[]>([
  {
    field: 'selection',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'id',
    label: t('product.id'),
    type: 'id',
    search: {
      hidden: true
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'cname',
    label: t('product.cname'),
    search: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'sku',
    label: t('product.sku'),
    form: {
      component: 'Input',
      formItemProps: {}
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'code',
    label: t('product.code'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  }
])

const getCategoryList = async () => {
  const res = await getCategorySelectTree()
  if (res) {
    categoryList.value = res.data.list
  }
}

const getBrandList = async () => {
  const res = await getBrandListApi({})
  if (res) {
    brandList.value = res.data.list
  }
}

const getFieldEnum = async () => {
  const res = await getFieldEnumApi({ field: 'all' })
  if (res) {
    fieldEnum.value = res.data
  }
}

const allSchemas = ref<AllSchemas>({
  formSchema: [] // 确保与接口匹配
})

const fetchData = async () => {
  await getCategoryList()
  await getBrandList()

  await getFieldEnum()

  const schemaConfig: SchemaConfig = {
    attachmentPreViewIdStore,
    tableDialogStoreID,
    tableDialogCurdSchema,
    brandList,
    fieldEnum,
    setValues,
    categoryList
  }
  const { crudSchemas } = useSchema(schemaConfig)
  const { allSchemas: newSchemas } = useCrudSchemas(crudSchemas)
  allSchemas.value = {
    formSchema: newSchemas.formSchema || []
  }
}

const rules: FormRules = reactive({})

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log('err', err)
  })
  if (valid) {
    const formData = await getFormData()
    formData.pid = tableDialogStore.selectedItems.map((item) => item.id)
    return formData
  }
}

const getTableDet = async () => {
  if (!query.id) {
    return
  }
  const res = await getInfoApi(query.id as string)
  if (props.index === 1) {
    // 新增数据
    delete (res.data as any).id
  }
  if (res) {
    // 在设置值之前转换数据类型
    const data = {
      ...res.data,
      billing_weight: res.data.billing_weight ? Number(res.data.billing_weight) : 0
    }
    await setValues(data)
    tableDialogStore.selectedItems = (data.product_accessories_linked_data || []).flatMap(
      (item: { id: number; cname: string }) => [{ id: item.id, title: item.cname }]
    )
  }
}

// 清空 store 数据
onBeforeUnmount(() => {
  tableDialogStore.reset()
})

onMounted(() => {
  if (route.meta.noCache) {
    getTableDet()
    fetchData()
  }
})

onActivated(() => {
  fetchData()
  getTableDet()
})

defineExpose({
  submit
})
</script>

<template>
  <Dialog
    v-model="attachmentPreViewIdStore.isPreViewVisible"
    :title="t('imageViewerDemo.imageViewer')"
    width="50%"
  >
    <img class="w-full" :src="attachmentPreViewIdStore.src" alt="Preview Image" />
  </Dialog>

  <Form :rules="rules" @register="formRegister" :schema="allSchemas.formSchema" />

  <TableDialog
    :getListApi="getListApi"
    :limit="tableDialogSelectedLimit"
    :isMultiple="true"
    :tableDialogStoreID="tableDialogStoreID"
    :itemTitleName="itemTitleName"
    row-key="id"
    :reserveSelection="true"
    :apiParams="{ type: 1 }"
  />
</template>

<style lang="less">
@import url('@/styles/global.less');
</style>
